from rest_framework.response import Response
import json
from rest_framework.views import APIView
from api import models
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import datetime
from .web_Form.AuctionMoldeForm import AuctionCreateForm, AuctionItemCreateForm
import uuid
from api import task
from django.db.models import F


class AuctionDeleteView(APIView):
    def post(self, request, *args, **kwargs):
        auction_id = json.loads(request.body.decode('utf8')).get('auction_id')
        if not auction_id:
            return Response({'status': False, 'message': "请传入有效id"})
        models.Auction.objects.filter(id=auction_id).delete()
        return Response({'status': True, 'message': '删除成功'})


@csrf_exempt
def AuctionItemImgDelete(request, pk):
    if request.method == "GET":
        iid = request.GET.get('iid')
        if not iid and pk:
            return JsonResponse({'status': False, 'message': '不欧克'})
        models.AuctionItemImage.objects.filter(item_id=pk, id=iid).delete()
        return JsonResponse({'status': True, 'message': 'ok'})


@csrf_exempt
def AuctionAdd(request):
    if request.method == "POST":
        content = json.loads(request.body.decode('utf8')).get('content')
        if content.get('id'):
            auction_obj = models.Auction.objects.filter(id=content['id']).first()
            form = AuctionCreateForm(data=content, instance=auction_obj)
        else:
            form = AuctionCreateForm(data=content)
            print(content)
        if form.is_valid():
            instance = form.save()
            # 1.定时任务,从 未开拍~预展
            preview_utc_datetime = datetime.datetime.utcfromtimestamp(
                form.instance.preview_start_time.timestamp())
            preview_task_id = task.to_preview_status_task.apply_async(args=[instance.id], eta=preview_utc_datetime).id
            # 2.定时任务,从 预展~开拍
            auction_utc_datetime = datetime.datetime.utcfromtimestamp(
                form.instance.auction_start_time.timestamp())
            auction_task_id = task.to_auction_status_task.apply_async(args=[instance.id], eta=auction_utc_datetime).id
            # 3.定时任务,从 开拍~结束
            auction_end_utc_datetime = datetime.datetime.utcfromtimestamp(
                form.instance.auction_end_time.timestamp())
            auction_end_task_id = task.end_auction_task.apply_async(args=[instance.id],
                                                                    eta=auction_end_utc_datetime).id

            # 将拍卖id保存到数据库中
            models.AuctionTask.objects.create(
                preview_task=preview_task_id,
                auction_task=auction_task_id,
                preview_end_task=auction_end_task_id,
                auction=instance
            )
            return JsonResponse({'status': True, 'message': '成功'})
        return JsonResponse({'status': False, 'message': form.errors.get_json_data()})


@csrf_exempt
def AuctionItemDeleteView(request, pk):
    auction_id = json.loads(request.body.decode('utf8')).get('auction_id')
    if not auction_id:
        return Response({'status': False, 'message': "请传入有效商品id"})
    if not pk:
        return Response({'status': False, 'message': "请传入有效拍品id"})
    print(pk)
    models.AuctionItem.objects.filter(id=auction_id, auction_id=pk).delete()
    models.Auction.objects.filter(id=pk).update(goods_count=F('goods_count') - 1)
    return JsonResponse({'status': True, 'message': '删除成功'})


@csrf_exempt
def AuctionItemAdd(request, pk):
    if not pk:
        return JsonResponse({'status': False, 'message': 'id为空'})
    if request.method == "POST":

        auction_obj = models.Auction.objects.filter(id=pk).first()
        if not auction_obj:
            return JsonResponse({'status': False, 'message': '不ok'})

        content = json.loads(request.body.decode('utf8')).get('content')

        content['auction'] = auction_obj
        # 创建拍品
        if not content.get('id'):
            form = AuctionItemCreateForm(data=content)
        else:
            auction_item_obj = models.AuctionItem.objects.filter(id=content['id'], auction=auction_obj).first()
            form = AuctionItemCreateForm(data=content, instance=auction_item_obj)
        if form.is_valid():
            form.instance.uid = str(uuid.uuid4())
            if not content.get('id'):
                form.instance.auction.goods_count += 1
                form.instance.auction.save()
            item = form.save()
            content.pop('auction')
            content['id'] = item.id
            content['status_name'] = item.get_status_display()
            # auction_item = form.save(commit=False)
            # auction_item.uid = str(uuid.uuid4())
            # auction_item.save()
            return JsonResponse({'status': True, 'message': content})
        return JsonResponse({'status': False, 'message': form.errors.get_json_data()})


@csrf_exempt
def AuctionItemDetail(request):
    if request.method == "POST":
        context = json.loads(request.body.decode('utf8'))
        did = context.get('id')
        print(context)
        auction_detail_obj = models.AuctionItemDetail.objects
        if not did:
            context.pop('id')
            auction_obj = auction_detail_obj.create(**context)
            return JsonResponse({'status': True, 'message': auction_obj.id})
        auction_detail_obj.filter(id=did, item_id=context['item_id']).update(value=context['value'], key=context['key'])
        return JsonResponse({'status': True, 'message': 'ok'})
